package jdbc.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import jdbc.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA
 * Description:学习使用C3P0连接池
 * User:22954
 * Date:2024-05-20
 * Time:14:59
 */
public class C3P0_ {
    @Test
    public void jdbc() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = JDBCUtils.getConnection();
            JDBCUtils.close(null, null, connection);
        }
        long end = System.currentTimeMillis();
        System.out.println("JDBC连接耗时:" + (end - start));//JDBC连接耗时:15502
    }

    @Test
    public void c3p0M1() throws IOException, PropertyVetoException, SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Properties properties = new Properties();
        properties.load(new FileInputStream("src/jdbc/mysql.properties"));
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        //连接管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);
        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        //设置最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            //获得连接
            Connection connection = comboPooledDataSource.getConnection();
//        System.out.println("Success");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0连接池方法一耗时:" + (end - start));//C3P0连接池方法一耗时:404
    }

    @Test
    public void c3p0M2() throws SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("JFIRE");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = comboPooledDataSource.getConnection();
//        System.out.println("Success");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0连接池方法二耗时:" + (end - start));//C3P0连接池方法二耗时:407
    }
}
